package com.kye.express.business.online_pay;

import android.content.Context;
import android.text.TextUtils;

import com.kye.express.R;
import com.kye.express.contract.base.BasePresenter;
import com.kye.express.contract.base.view.RxView;
import com.kye.model.OpenApiResultObserver;
import com.kye.model.UserSession;
import com.kye.model.base.RetrofitManager;
import com.kye.model.bean.OpenApiResult;
import com.kye.model.bean.invoice_online.GeneratedInvoiceDataResultBean;
import com.kye.model.bean.invoice_online.GetInvoicedListResultBean;
import com.kye.model.bean.invoice_online.RequestFindWaybillAmountBean;
import com.kye.model.bean.invoice_online.RequestGeneratedInvoiceDataBean;
import com.kye.model.bean.invoice_online.RequestGetInvoicedListBean;
import com.kye.model.bean.online.GetPayResultResultBean;
import com.kye.model.bean.online.GetUnpaidFreightListResultBean;
import com.kye.model.bean.online.GetWaybillPayMoneyResultBean;
import com.kye.model.bean.online.request.RequestGetPayResultBean;
import com.kye.model.bean.online.request.RequestGetUnpaidFreightListBean;
import com.kye.model.bean.online.request.RequestGetWaybillPayMoneyBean;
import com.kye.model.bean.user.User;
import com.kye.model.constant.Constants;
import com.kye.model.service.InvoiceOnlineService;
import com.kye.model.service.OnlinePayService;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

public interface OnlinePayActivityContract {

    interface OnlinePayActivityView extends RxView {

        void onComplete(boolean isLoadMore);

        void onLoading();

        void onLoaded(GetUnpaidFreightListResultBean datas, boolean isLoadMore);

        void onError(String msg, boolean isLoadMore);

        void onOtherError(String msg);

        void onCompleteFindWaybillAmount();

        void onLoadedFindWaybillAmount(List<GetUnpaidFreightListResultBean.DatasBean> datas);

        void onErrorFindWaybillAmount(String msg);

        void onLoadedGetPayResult(GetPayResultResultBean data);
    }

    class OnlinePayActivityViewPresenter extends BasePresenter<OnlinePayActivityContract.OnlinePayActivityView> {

        private Context mContext;
        private int mCurrentPage = 1;

        public OnlinePayActivityViewPresenter(Context context) {
            this.mContext = context;
        }

        /**
         * 查询运费
         */
        public void getUnpaidFerigetList(final boolean isFirstIn, final boolean isLoadMore, String no) {
            String phone = "";
            User user = UserSession.getInstance().getUser();
            if (user != null) {
                phone = user.getPhone();
                if (TextUtils.isEmpty(no)) {
                    no = user.getCustomCode();
                }
            }

            RetrofitManager.getInstance().createOpenApiService(OnlinePayService.class)
                    .getUnpaidFerigetList(new RequestGetUnpaidFreightListBean(phone, no, Constants.PAGE_SIZE, isLoadMore ? (mCurrentPage + 1) : 1))
                    .compose(getView().<OpenApiResult<GetUnpaidFreightListResultBean>>bindToLifecycleDestroy())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new OpenApiResultObserver<GetUnpaidFreightListResultBean>() {

                        @Override
                        public void onLoading(Disposable d) {
                            if (isFirstIn) {
                                getView().onLoading();
                            }
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().onError(mContext.getString(R.string.common_net_error), isLoadMore);
                        }

                        @Override
                        public void onLoaded() {
                            if (getView() != null) {
                                getView().onComplete(isLoadMore);
                            }
                        }

                        @Override
                        public void onSuccess(OpenApiResult<GetUnpaidFreightListResultBean> result, GetUnpaidFreightListResultBean datas) {
                            if (!isLoadMore) {
                                resetPage();
                            }
                            if (datas != null) {
                                getView().onLoaded(datas, isLoadMore);
                                if (isLoadMore) {
                                    setCurrentPage(mCurrentPage + 1);
                                }
                            } else {
                                getView().onError(mContext.getString(R.string.common_no_more_datas), isLoadMore);
                            }
                        }

                        @Override
                        public void onApiError(OpenApiResult<GetUnpaidFreightListResultBean> result, int code, String msg) {
                            if (!TextUtils.isEmpty(msg)) {
                                getView().onError(msg, isLoadMore);
                            } else {
                                getView().onError(mContext.getString(R.string.common_net_error), isLoadMore);
                            }
                        }

                    });
        }

        public int getCurrentPage() {
            return mCurrentPage;
        }

        public void setCurrentPage(int currentPage) {
            this.mCurrentPage = currentPage;
        }

        public void resetPage() {
            setCurrentPage(1);
        }


        /**
         * 查询运单需要支付的费用等信息
         */
        public void findWaybillAmount(String waybill) {
            String phone = "";
            User user = UserSession.getInstance().getUser();
            if (user != null) {
                phone = user.getPhone();
            }

            RetrofitManager.getInstance().createOpenApiService(OnlinePayService.class)
                    .getWaybillPayMoney(new RequestGetWaybillPayMoneyBean(waybill, phone))
                    .compose(getView().<OpenApiResult<List<GetWaybillPayMoneyResultBean>>>bindToLifecycleDestroy())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new OpenApiResultObserver<List<GetWaybillPayMoneyResultBean>>() {

                        @Override
                        public void onLoading(Disposable d) {
                            getView().onLoading();
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().onOtherError(mContext.getString(R.string.common_net_error));
                        }

                        @Override
                        public void onLoaded() {
                            if (getView() != null) {
                                getView().onCompleteFindWaybillAmount();
                            }
                        }

                        @Override
                        public void onSuccess(OpenApiResult<List<GetWaybillPayMoneyResultBean>> result, List<GetWaybillPayMoneyResultBean> datas) {
                            if (datas != null && datas.size() > 0) {
                                //由于后台返回的结构体字段名不一样，所以这里做一个数据处理
                                List<GetUnpaidFreightListResultBean.DatasBean> datasBeans = new ArrayList<GetUnpaidFreightListResultBean.DatasBean>();
                                GetWaybillPayMoneyResultBean getWaybillPayMoneyResultBean = datas.get(0);
                                if (getWaybillPayMoneyResultBean != null) {
                                    GetUnpaidFreightListResultBean.DatasBean datasBean = new GetUnpaidFreightListResultBean.DatasBean();
                                    datasBean.setWaybill(getWaybillPayMoneyResultBean.getWaybill());
                                    datasBean.setAdvancePayment(getWaybillPayMoneyResultBean.getMoney());
                                    datasBean.setSendTime(getWaybillPayMoneyResultBean.getSendinTime());
                                    datasBeans.add(datasBean);
                                }
                                getView().onLoadedFindWaybillAmount(datasBeans);
                            }else{
                                getView().onOtherError(mContext.getString(R.string.common_no_datas));
                            }
                        }

                        @Override
                        public void onApiError(OpenApiResult<List<GetWaybillPayMoneyResultBean>> result, int code, String msg) {
                            if (!TextUtils.isEmpty(msg)) {
                                getView().onErrorFindWaybillAmount(msg);
                            } else {
                                getView().onErrorFindWaybillAmount(mContext.getString(R.string.common_net_error));
                            }
                        }

                    });
        }


        /**
         * 查询支付结果
         */
        public void findPayResult(String orderNo) {
            String phone = "";
            User user = UserSession.getInstance().getUser();
            if (user != null) {
                phone = user.getPhone();
            }

            RetrofitManager.getInstance().createOpenApiService(OnlinePayService.class)
                    .getPayResult(new RequestGetPayResultBean(phone, orderNo))
                    .compose(getView().<OpenApiResult<GetPayResultResultBean>>bindToLifecycleDestroy())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new OpenApiResultObserver<GetPayResultResultBean>() {

                        @Override
                        public void onLoading(Disposable d) {
                            getView().onLoading();
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().onOtherError(mContext.getString(R.string.online_pay_get_pay_result_failed));
                        }

                        @Override
                        public void onLoaded() {
                            if (getView() != null) {
                                getView().onCompleteFindWaybillAmount();
                            }
                        }

                        @Override
                        public void onSuccess(OpenApiResult<GetPayResultResultBean> result, GetPayResultResultBean datas) {
                            if (datas != null) {
                                getView().onLoadedGetPayResult(datas);
                            }else{
                                getView().onOtherError(mContext.getString(R.string.online_pay_get_pay_result_failed));
                            }
                        }

                        @Override
                        public void onApiError(OpenApiResult<GetPayResultResultBean> result, int code, String msg) {
                            if (!TextUtils.isEmpty(msg)) {
                                getView().onOtherError(msg);
                            } else {
                                getView().onOtherError(mContext.getString(R.string.online_pay_get_pay_result_failed));
                            }
                        }

                    });
        }

    }
}
